$(function(){
    layui.use(['element','jquery', 'form', 'layer', 'table'], function(){
        var $ = layui.jquery,  laytpl = layui.laytpl, layer = layui.layer,  element = layui.element;

        //面页
        const PAGE = {
            department:{
                src: 'toStatistics',
                data:{reportId:1 },
                title:'机构统计表',
                concurrent: 1,
            },
            evaluate:{
                src: 'toStatistics',
                data:{reportId:3 },
                title:'评估统计表',
                concurrent: 1
            },
            home:{
                src: 'toStatistics',
                data:{reportId:2 },
                title:'居家统计表',
                concurrent: 1,
            },
            settlement:{
                src: 'toSettlement',
                title:'结算统计表',
                concurrent: 1,
            },
            total_expense:{
                src: 'toExpense',
                title:'所有费用统计',
                concurrent: 1,
            },

            upload:{
                src: 'toUploadFile',
                title:'文件上传',
                concurrent: 1, //同时能打开的面页数量, 未定义表示不限制
            },

            dataOverview:{
                src: 'toDataOverview',
                title:'数据总览',
                concurrent: 1,
            },
            monthly:{
                src: 'toMonthly',
                title:'月报',
                concurrent: 1,
            },

            getUrl:function (page) {
                if(page.data){
                    return page.src + '?' + $.param(page.data);
                }
                return page.src;

            }

        };

        /**
         * 导航器
         * @type {{to: function}}
         */
        let Navigator = (function () {
            const PAGE_CONTENT = $('script#iframePage')[0].innerHTML;


            //缓存已经打开的面页数量, 防止多次打开
            const CACHE = {};

            //pageId转Page名字
            const PAGE_ID_TO_PAGE_NAME = {};

            //加载loading content
            const LOADING_CONTENT = $('#loadingLayer')[0].innerHTML;

            //监听Tab选项卡删除事件
            element.on('tabDelete(contentTab)', function(data){
                // console.log(this); //当前Tab标题所在的原始DOM元素
                // console.log(data.index); //得到当前Tab的所在下标
                // console.log(data.elem); //得到当前的Tab大容器
                let pageId = $(this).parent().attr('lay-id');
                // console.log('面页关闭', pageId);
                if(pageId in PAGE_ID_TO_PAGE_NAME){
                    let pageName = PAGE_ID_TO_PAGE_NAME[pageId];
                    if(CACHE[pageName]){
                        CACHE[pageName] = CACHE[pageName] - 1;
                    }
                    //上传面页关闭
                    if(pageName == 'dataOverview'){
                        $('div.upload:first').hide(); //FIXME 修改成事件驱动
                    }
                }
            });

            return {
                to: function(pageName){
                    // let pageName = setting.pageName;
                    let page = PAGE[pageName];
                    if(!page){return {error: '错误'};}

                    //检查缓存(防止打开过多的面页造成卡顿)
                    if(page.concurrent){
                        if(CACHE[pageName] && CACHE[pageName] >= page.concurrent){
                            return {error: '不能再打开更多的面页'}
                        }
                        CACHE[pageName] = CACHE[pageName]?CACHE[pageName]+1:1;
                    }

                    let html = laytpl(PAGE_CONTENT).render({src: PAGE.getUrl(page)});
                    // contentWindow

                    let pageId = Date.now();
                    let iframe = $(html);
                    // console.log('iframe', iframe);


                    element.tabAdd('contentTab', {
                        title: page.title,
                        content: LOADING_CONTENT,
                        id: pageId
                    });
                    // console.log(a);
                    element.tabChange('contentTab', pageId);

                    //将pageId储存
                    PAGE_ID_TO_PAGE_NAME[pageId] = pageName;

                    //查找添加的div
                    let content = (function () {
                        let title = $('#contentTab>ul>li[lay-id=' + pageId + ']');
                        // console.log('title', title);
                        return $('#contentTab>div.layui-tab-content').children().eq(title.index());
                    })();
                    // console.log('content', content);
                    if(content.length > 0){
                        //监听iframe加载完成
                        iframe.on('load', function () {
                            // console.log('iframe', pageId, '加载完成');
                            content.find('>.loading-area').remove();
                            // //上传面页打开
                            // if(pageName == 'dataOverview'){
                            //     $('div.upload:first').show(); //FIXME 修改成事件驱动
                            // }

                        });
                        // iframe[0].window;
                        // console.log('iframe', iframe);
                        //加入ifrmae
                        content.append(iframe);

                        //大小重置为content大小
                        let iframeWindow = iframe[0].contentWindow || iframe[0].contentDocument.parentWindow;
                        iframeWindow.resizeWindowHeight = function(){
                            iframe[0].height = this.document.documentElement.scrollHeight || this.document.body.scrollHeight;
                        };

                    }else{
                        return{
                            error: '发生错误了'
                        }
                    }


                    return {
                        iframe: iframe,
                        pageId: pageId
                    }
                }

            };
        })();


        //上传按钮点击
        // let uploadPageId = 0;
        // $('#upload-switch-button').on('click', (res)=>{
        //     console.log('点击上传开关按钮');
        //     let page = Navigator.to('upload');
        //     if(page.error){
        //         if(uploadPageId > 0){
        //             element.tabChange('contentTab',uploadPageId);
        //         }
        //     }else{
        //         uploadPageId = page.pageId;
        //     }
        //
        //
        // });
        // $('div.upload:first').hide(); //初始隐藏

        //报表按钮点击
        $('.layui-colla-item .layui-colla-content a').on('click', (res)=>{
            // console.log('报表按钮点击', res);
            let target = $(res.currentTarget);
            let name = target.data().page;
            // console.log(name);
            if(name){
                let page = Navigator.to(name);
                if(page.error){
                    layer.msg(page.error, {icon: 5});
                    // console.log('打开面页出错,', page.error);
                }
            }


        });


        //初始加载面页
        // let page = navigator.to('dataOverview');
        // if(page.error){
        //     console.log('打开面页出错,', page.error);
        // }
    });
});